<?php
class model_lhbase_units extends gdl_components_basemodel 
{

    public function primarykey() {
        return 'id';
    }

    public function tableName() {
        return 'lh_units';
    }
	public function getInfoArg($arrg=[],$field)
    {
		if(empty($arrg)) return false;
		return $this->select($arrg, $field)->items;
    }
	
	/*权限列表
	*$admin string zg总管理员 gl单位管理员其他的暂定
	*platformId int 平台id
	*unitid 部门id
	*
	*/
	 public function getMenu($admin='gl',$platformId,$unitid=0)

    {
		$adminuser = new model_lhbase_adminuser();

		$unitArr = $adminuser->select(['platformId'=>$platformId], 'unitId,count(*) num','group by unitId  order by unitId desc')->items;
		$nodes = $this->getInfoArg(['platformId'=>$platformId,'status'=>1,'isDelete'=>1],"id,parentId,unitName,status,level"); //获取当前平台所有架构
		$list = [];
		if($admin=='zg'){
			if($unitid){
				$adminUnitsId = $this->operating($platformId,$unitid);
				foreach($nodes as $v){
				$list[$v['id']] = [
						'id'=>$v['id'],
						'pid'=>$v['parentId'],
						'name'=>$v['unitName'],
						'status'=>$v['status'],
						'level'=>$v['level'],
						'operat'=>in_array($v['id'],$adminUnitsId) ? 1 : 2, //是否可操作1是可以 2是不可以
						'hasChildren'=>2, //1表示有子数组 2表示没有
						'num'=>0,//人数
						];
						if(!empty($list[$v['parentId']])){
							$list[$v['parentId']]['hasChildren']=1;
						}
				}
			} else {
				foreach($nodes as $v){
					$list[$v['id']] = [
							'id'=>$v['id'],
							'pid'=>$v['parentId'],
							'name'=>$v['unitName'],
							'status'=>$v['status'],
							'level'=>$v['level'],
							'operat'=>1, //是否可操作1是可以 2是不可以
							'hasChildren'=>2, //1表示有子数组 2表示没有
							'num'=>0,//人数
							];
							if(!empty($list[$v['parentId']])){
								$list[$v['parentId']]['hasChildren']=1;
							}
				}
			}
		} else {
			$Checks_yes = $this->operating($platformId,$unitid);
			foreach($nodes as $v){
				$list[$v['id']] = [
						'id'=>$v['id'],
						'pid'=>$v['parentId'],
						'name'=>$v['unitName'],
						'status'=>$v['status'],
						'level'=>$v['level'],
						'operat'=>in_array($v['id'],$Checks_yes) ? 1 : 2, //是否可操作1是可以 2是不可以
						'hasChildren'=>2, //1表示有子数组 2表示没有
						'num'=>0,//人数
						];
				if(!empty($list[$v['parentId']])){
					$list[$v['parentId']]['hasChildren']=1;
				}
			}
		}
		/****写入每个部门人数*****/
		foreach($unitArr as $vu){
			$id = empty($list[$list[$vu['unitId']]['pid']]) ? 0 : $list[$vu['unitId']]['pid'];
			//$list[$vu['unitid']]['num'] = $vu['num']; //分别显示每个组人数的就用这个
			$list[$vu['unitId']]['num'] += $vu['num'];
			if(!empty($list[$list[$vu['unitId']]['pid']])){
				$list[$id]['num'] += $vu['num'];
			}
		}
		/****写入每个部门人数 end*****/
		return $list;
    }
	
	/*权限列表【不显示所有列表】
	*$admin string zg总管理员 gl单位管理员其他的暂定
	*platformId int 平台id
	*unitid 部门id
	*
	*/
	public function getMenuSpecial($admin='gl',$platformId,$unitid=[0],$title='')

    {
		$platformId = intval($platformId);
		$adminuser = new model_lhbase_adminuser();
		$authuserunits = new model_lhbase_authuserunits();
		$leftJoin = array(
		$authuserunits->tableName().' as a' => $adminuser->tableName().'.id = a.adminUserId'
		);
		
		$unitArr = $adminuser->select([$adminuser->tableName().'.platformId'=>$platformId], 'a.unitsId unitId,count(*) num','group by a.unitsId  order by a.unitsId desc','',$leftJoin)->items;
		 //获取当前平台所有架构
		$list = [];
		$condition = 'platformId='.$platformId.' and isDelete=1';
		$searchs = [0];

		
		if($admin=='zg'){
			if($title!=''){
				$searchs = $this->searchs($title,$platformId);
				$condition.=' and id in('.implode(',',$searchs).')';
			}
			
			$nodes = $this->getInfoArg($condition,"id,parentId,unitName,status,level");
			foreach($nodes as $v){
				$list[$v['id']] = [
						'id'=>$v['id'],
						'pid'=>$v['parentId'],
						'title'=>$v['unitName'],
						'status'=>$v['status'],
						'level'=>$v['level'],
						'operat'=>1, //是否可操作1是可以 2是不可以
						'hasChildren'=>2, //1表示有子数组 2表示没有
						'num'=>0,//人数
						];
						if(!empty($list[$v['parentId']])){
							$list[$v['parentId']]['hasChildren']=1;
						}
			}
		} else {
			//$Checks_yes = $this->operating($platformId,$unitid);
			$getSuperior = $this->getSuperior($platformId,$unitid);
			//$currentId = array_merge($Checks_yes,$getSuperior);
			$currentId = array_merge($unitid,$getSuperior);
			if($title!=''){
				$searchs = $this->searchs($title,$platformId,$currentId);
				$condition.=' and id in('.implode(',',$searchs).')';
			} else {
				$condition.=' and id in('.implode(',',$currentId).')';
			}

			$nodes = $this->getInfoArg($condition,"id,parentId,unitName,status,level");

			foreach($nodes as $v){
				$list[$v['id']] = [
						'id'=>$v['id'],
						'pid'=>$v['parentId'],
						'title'=>$v['unitName'],
						'status'=>$v['status'],
						'level'=>$v['level'],
						'operat'=>in_array($v['id'],$unitid) ? 1 : 2, //是否可操作1是可以 2是不可以
						'hasChildren'=>2, //1表示有子数组 2表示没有
						'num'=>0,//人数
						];
				if(!empty($list[$v['parentId']])){
					$list[$v['parentId']]['hasChildren']=1;
				}
			}
		}
		/****写入每个部门人数*****/
		foreach($unitArr as $vu){
//			$id = empty($list[$list[$vu['unitId']]['pid']]) ? 0 : $list[$vu['unitId']]['pid'];
			$id = 0;
			//$list[$vu['unitid']]['num'] = $vu['num']; //分别显示每个组人数的就用这个
			if(!empty($list[$vu['unitId']])){
			$list[$vu['unitId']]['num'] += $vu['num'];
				if(!empty($list[$list[$vu['unitId']]['pid']])){
				    if (!isset($list[$id])){
                        continue;
                    }else{
                        $list[$id]['num'] += $vu['num'];
                    }
				}
			}
		}
		/****写入每个部门人数 end*****/
		return $list;
    }
	
	
	
	/*获取用户可操作单位id
	*platformId int 平台id
	*unitid 部门id
	*
	*/
	public function operating($platformId,$unitid=0)
	{
		if(is_array($unitid)){
			$nodes = $this->select('platformId='.$platformId.' and isDelete=1 and id in('.implode(',',$unitid).')',"level,id")->items;
		} else {
			$nodes = $this->select(['platformId'=>$platformId,'isDelete'=>1,'id'=>$unitid],"level,id")->items;
		}
			
		$list = [0];
		if(empty($nodes)) return $list;
		$list = array_column($nodes,'id');
		//$level = $this->getInfoArg("platformId='{$platformId}' and isDelete=1 and level>".$nodes['level'],"id,parentId",'order by level asc'); 
		$level = $this->getInfoArg("platformId='{$platformId}' and isDelete=1","id,parentId",'order by level asc'); 
	
		//获取低于当前层级的数据
		foreach($level as $v){
			if(in_array($v['parentId'],$list)){
				$list[] = $v['id']; //获取当前用户可操作单位id
			}
		}
		
		return $list;
    }
	
	/*获取所有部门id，name
	*platformId int 平台id
	*
	*
	*/
	public function unitsDetails($platformId,$units_id)
	{			

				$list = [];
				if(empty($units_id)) return $list;
				$units_name = $this->getInfoArg('platformId='.$platformId.' and id in('.implode(',',$units_id ).')','id, unitName name');
				foreach($units_name as $v){
					$list[$v['id']] = $v['name'];
				}
		
				return $list;
    }
	
	/*获取所有部门id
	*platformId int 平台id

	*
	*/
	public function adminunits($platformId)
	{			
				$list = [0];
				$condition = ['platformId'=>$platformId,'status'=>1,'isDelete'=>1];
				$adminunits = $this->select($condition,'id')->items;
				foreach($adminunits as $v){
					$list[] = $v['id'];
				}
		
		return $list;
    }
	
	/*获取当前用户所有上级id
	*platformId int 平台id
	*unitid 部门id
	*
	*/
	public function getSuperior($platformId,$unitid=[0])
	{
		if(is_array($unitid)){
			$nodes = $this->select('platformId='.$platformId.' and isDelete=1 and id in('.implode(',',$unitid).')',"level,id,parentId")->items;
		} else {
			$nodes = $this->select(['platformId'=>$platformId,'isDelete'=>1,'id'=>$unitid],"level,id,parentId")->items;
			$nodes = $this->selectOne(['platformId'=>$platformId,'isDelete'=>1,'id'=>$unitid],"level,id,parentId");
		}
			
		$list = [0];
		if(empty($nodes)) return $list;
		$list = array_column($nodes,'id');
		$pid =  array_column($nodes,'parentId');
		$level = $this->getInfoArg("platformId='{$platformId}'  and isDelete=1","id,parentId",'order by level asc'); //获取低于当前层级的数据
		foreach($level as $v){
			if(in_array($v['id'],$pid)){
				$list[] = $v['id']; //获取当前用户可操作单位id
				$pid[] = $v['parentId'];
			}
		}
		
		return $list;
    }
	
	//获取能操作的部门
	public function enabled($userid,$reg,$unitid=0)
	{
		$adminuser = new model_lhbase_appadminuser();
		$authuserunits = new model_lhbase_authuserunits();
		$admin = $adminuser->selectOne(['id'=>$userid,'adminReg'=>$reg],'id,characters,platformId,unitsId');
		
		
		
			if(empty($admin['id'])){
				$data = ['code'=>'n','msg'=>'帐号错误','mark'=>[]];
				return $data;
			}
			$unitsId = $authuserunits->select(['adminUserId'=>$userid],'unitsId')->items;
			
			$unitIds = empty($unitsId) ? [0] : array_column($unitsId,'unitsId');
			if(!$unitid){
				$unitid = $unitIds[0];
			}
			if($admin['characters']!='zg' || ($admin['characters']=='zg' && $admin['unitsId'])){ //非平台管理员需要检查权限
				$operating = $this->operating($admin['platformId'],$unitIds);//

				if(!in_array($unitid,$operating)){
					
					$data = ['code'=>'n','msg'=>'没有修改权限','mark'=>[]];
					return $data;
				}
			}
		return ['code'=>'y','msg'=>'可以操作','mark'=>$admin];
    }
	
	
	
	/*获取用户可操作单位id
	*platformId int 平台id
	*datas 操作的部门集合
	*
	*/
	public function depart($datas,$platformId,$userid,$pid=0,$level=0)
	{
		$globas = new service_globals();
		$adminrole = new model_lhbase_adminrole();
		$pinyin = new service_pinyin();

		$datime = time();
		try {
			foreach($datas as $v){
				$v['name'] = $globas->getStr($v['name']);
				if($v['id']){ //修改
					$id= intval($v['id']);
					$data = [
							'name'=>$pinyin->getFirstPY($v['name']),
							'unitName'=> $v['name'],//'单位名',
							'updateTime'=> $datime,//'更新时间',
							];
					
					$this->update(['id' => $id],$data);
					usleep(100);
				} else if(!empty($v['name'])){ //添加
					$names = $pinyin->getFirstPY($v['name']);
					$reg = $globas->get_random().$names;
					$data = [
							'unitCode'=>$names,
							'platformId'=>$platformId,
							'parentId'=>$pid,//'上级单位id',
							'unitName'=> $v['name'],//'单位名',
							'createTime'=> $datime,//'单位创建时间',
							'updateTime'=> $datime,//'更新时间',

							'level'=> $level,//'第几级（暂定）',
							'userId'=>$userid,
							];
					$id = $this->insert($data);
					$adminrole->insert([
						'changes'=> 1,
						'name'=> 'Administrator',//'名称',
						'platformId'=> $platformId,//'平台ID',
						'isDelete'=> 1,
						'createTime'=> $datime,//'添加时间',
						'updateTime'=> $datime,//'更新时间',
						'unitsId'=> $id,//'单位iid',
	
						'status'=>$v['status'],
					]);
					usleep(100);
				}
				if(!empty($v['child']) && is_array($v['child'])){
					self::depart($v['child'],$platformId,$userid,$id,($level+1));
				}
			}
		} catch (Exception $e) {

        }
		
		return true;
    }
	//获取指定平台下所有单位
	public function getLIst($platformId=0)
    {
		if(!$platformId) return false;
		$res = $this->select(['platformId'=>$platformId,'status'=>1,'isDelete'=>1],'id,unitName,parentId')->items;
		
		return $res;
    }
	
	//获取可以操作的单位名
	public function managements($list=[],$userid,$platformId)
    {
		if(empty($list)) return [];
		$adminroleuser = new model_lhbase_adminroleuser();
		$adminrole = new model_lhbase_adminrole();
		$adminuser = new model_lhbase_appadminuser();

		$adminIdentity = $adminuser->selectOne(['id'=>$userid],'characters,unitsId');
		$role = $adminrole->getLIstadmin($platformId);
		$unitidList = [];
		if($adminIdentity['characters']=='zg'){
			$unitidList=[0];
			if($unitsAdmin['unitsId']){
			$unitidList = $this->operating($platformId,$adminIdentity['unitsId']);

			}
			
		} else {
			$unitid = $adminroleuser->select(['userId'=>$userid],'unitId')->items;
			
			foreach($unitid as $v){ //获取当前管理员所在的单位
				$unitidList[] = $v['unitId'];
			}
		}
		$res = [];
		foreach($list as $vl){
			if(in_array($vl['parentId'],$unitidList)){
				$unitidList[] = $vl['id'];
				$res[] = [
							'id'=>$vl['id'],
							'title'=>$vl['unitName'],
							'groupsId'=>empty($role[$vl['id']]) ? 0 : $role[$vl['id']],
							];
				
			}
		}
		
		
		return $res;
    }
	function searchs($title='',$platformId,$id=[]){
			$searchs = [0];
			$condition = "unitName like '%{$title}%' and platformId=".$platformId;
			if(!empty($id)){
				$condition .= ' and id in ('.implode(',',$id).')';
			}
			$unit_sr_id = $this->getInfoArg($condition,'id');
			foreach($unit_sr_id as $v){
				$Checks_yes = $this->operating($platformId,$v['id']);
				$getSuperior = $this->getSuperior($platformId,$v['id']);
				usleep(100); //所谓的预留后面大优化 (*^_^*)
				$searchs = array_merge($searchs,$Checks_yes);
				$searchs = array_merge($searchs,$getSuperior);
			}
			
		return $searchs;
	}
	
	//根据权限组id 删除所有对应的权限
	public function subordinateId($groupId) {
			if(empty($groupId)) return [0];
			$authgroupaccess = new model_lhbase_authgroupaccess();
			if(is_array($groupId)){
				$uId = $authgroupaccess->select('groupId in('.implode(',',$groupId).')','uId')->items;
			} else {
				$uId = $authgroupaccess->select(['groupId'=>$groupId],'uId')->items;
			}
			$userId = [0];
			if(!empty($uId)){
				$userId = array_column($uId,'uId');
				$userId = self::deleteRuleUser($userId);
			}
		return $userId;
		
	}
	
	public function deleteRuleUser($userid,$userSetId=[0]) {
		if(empty($userid)) return $userSetId;
		
		$authgroup = new model_lhbase_authgroup();
		$authgroupaccess = new model_lhbase_authgroupaccess();
		//$userId = array_column($uId,'uId');
		/******第一步先查出来每个管理员有多少权限组**********/
		$attributionId = $authgroup->select('attribution in('.implode(',',$userid).')','id')->items;
		if(empty($attributionId)){
			 return $userSetId;
		}
		$userSetId = array_merge($userSetId,$userid);
		$attribution = empty($attributionId) ? [0] : array_column($attributionId,'id');
		
		/******第二步权限组绑定那些管理员**********/
		$uId = $authgroupaccess->select('groupId in('.implode(',',$attribution).')','uId')->items;
		if(!empty($uId)){
			$userId =array_diff(array_column($uId,'uId'),$userSetId); //防止手动写了一条造成死循环的 数据关联
			$userSetId = self::deleteRuleUser($userId,$userSetId);
		}

		return $userSetId;

	}
	
}
